package openhaven.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import openhaven.control.LoginTask;
import openhaven.control.TaskProcessor;
import openhaven.control.message.RemoteMessageWorker;
import openhaven.control.net.Message;

import org.apache.log4j.Logger;

public class HavenFrame
{
    private final Logger log = Logger.getLogger(HavenFrame.class);
    private final JFrame frame;
    private final ResourceBundle bundle;
    private final String configFileLocation = "config";

    public HavenFrame()
    {
        bundle = ResourceBundle.getBundle(configFileLocation);
        frame = new JFrame();
        final int width = Integer.parseInt(getProp("window.width"));
        final int height = Integer.parseInt(getProp("window.height"));
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        showLoginPage();
        frame.setVisible(true);
    }

    private void showLoginPage()
    {
        final JPanel loginPanel = new JPanel();
        frame.getContentPane().add(loginPanel);
        final JTextField host = new JTextField(getProp("host"));
        loginPanel.add(host);
        final JTextField username = new JTextField(getProp("username"));
        loginPanel.add(username);
        final JTextField password = new JPasswordField(getProp("password"));
        loginPanel.add(password);
        final JButton go = new JButton("go");
        loginPanel.add(go);
        go.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(final ActionEvent arg0)
            {
                final BlockingQueue<Message> uiMessageQueue = new LinkedBlockingQueue<Message>();
                TaskProcessor.execute(new RemoteMessageWorker(HavenFrame.this, uiMessageQueue));
                TaskProcessor.execute(new LoginTask(host.getText(), username.getText(), password.getText(), uiMessageQueue));

            }
        });
    }

    private String getProp(final String name)
    {
        return bundle.getString(name);
    }
}
